import { TreeNode } from 'primeng/primeng';
import { RefBean, Selectable, RefBeanTreeNode } from '../models';

export class PrimengUtils {
	/** 把PrimeNg TreeNode数组转换成RefBean数组
	 * @param treeNodes PrimeNg TreeNode数组，有data,label两个属性
	 * @return RefBean数组， 有code 和 name两个属性
	 */
	public static treeNodesToRefBeans(treeNodes: TreeNode[]): RefBean[] {
		let refBeans: RefBean[] = new Array<RefBean>();
		for (let tnode of treeNodes) {
			refBeans.push(new RefBean(tnode.data, tnode.label));
		}
		return refBeans;
	}
	/** 根据已选的数据，把相应的PrimeNg TreeNode节点打上已选标记
	 * @param treeNodes PrimeNg TreeNode数组，有data,label两个属性
	 * @return RefBean数组， 有code 和 name两个属性
	 */
	public static getSelectedTreeNodeByDatas(tree: TreeNode[], datas: string[]): TreeNode[] {
		let seletedTreeNodes: TreeNode[] = new Array<TreeNode>();
		PrimengUtils.getSelectedTreeNodeByDatas1(tree, datas, seletedTreeNodes);
		return seletedTreeNodes;
	}
	private static getSelectedTreeNodeByDatas1(treeNodes: TreeNode[], datas: string[], seletedTreeNodes: TreeNode[]) {
		for (let tnode of treeNodes) {
			for (let data of datas) {
				if (data == tnode.data) {
					seletedTreeNodes.push(tnode);
					break;
				}
			}
			if (tnode.children) {
				PrimengUtils.getSelectedTreeNodeByDatas1(tnode.children, datas, seletedTreeNodes);
			}
		}

	}
	/** 从tree中找到与refBeans数组中ID相同的节点集。
	 * @param tree 目标树，Primeng TreeNode树
	 * @param refBeans 对应的refBeans，有code,name两个属性
	 * @return PrimeNg TreeNode树中，和refBeans中有相同ID的节点集
	 */
	public static getSelectedTreeNodes(tree: TreeNode[], refBeans: RefBean[]): TreeNode[] {
		let seletedTreeNodes: TreeNode[] = new Array<TreeNode>();
		PrimengUtils.getSelectedNodes(tree, refBeans, seletedTreeNodes);
		return seletedTreeNodes;
	}
	private static getSelectedNodes(treeNodes: TreeNode[], refBeans: RefBean[], seletedTreeNodes: TreeNode[]) {
		for (let tnode of treeNodes) {
			for (let rbean of refBeans) {
				if (rbean.code == tnode.data) {
					seletedTreeNodes.push(tnode);
					break;
				}
			}
			if (tnode.children) {
				PrimengUtils.getSelectedNodes(tnode.children, refBeans, seletedTreeNodes);
			}
		}

	}
	/** 把从服务器来的RefBeanTreeNode树变成PrimeNg TreeNode树，实际只是简单的把RefBean的code和name属性复制到data,label属性。
	 * 这样简单处理后，需要返回到服务器端时，可以把PrimeNg TreeNode树直接当作RefBeanTreeNode树返回，无需变换。
	 * @param rNodes 从服务器来的RefBean树，有code,name两个属性
	 * @return PrimeNg TreeNode树， 有data 和 label两个属性
	 */
	static refBeanTreeNodesToTreeNodes(rNodes: RefBeanTreeNode[]): TreeNode[] {
		//let tnodes = new Array<TreeNode>();
		for (let rnode of rNodes) {
			let tnode: TreeNode = rnode;
			tnode.data = rnode.code;
			tnode.label = rnode.name;
			//tnodes.push(tnode);
			if (rnode.children) {
				tnode.children = PrimengUtils.refBeanTreeNodesToTreeNodes(rnode.children);
			}
		}
		return rNodes;
	}
}